#                ,            
#   _  _/_ __    __   _   _  
#  /_)_(__/ (__(_/ (_(_/_/_)_
#                   .-/      
#                  (_/       
#
#  http://stringswiki.com
#  Understanding the simplicity
#  Copyright 2009, Asbjorn Enge. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#  MA  02111-1307  USA
#
#  (C) 2009
"""

	router.py - URL Router


"""
__author__  = 'Asbjorn Enge <asbjorn@hanafjedle.net>'

import re, sys, os, mimetypes

var_regex = re.compile(r"""
	\{          # The exact character "{"
	(\w+)       # The variable name (restricted to a-z, 0-9, _)
	(?::([^}]+))? # The optional :regex part
	\}          # The exact character "}"
	""", re.VERBOSE)
	
def template_to_regex(template):
	regex = ''
	last_pos = 0
	for match in var_regex.finditer(template):
		regex += re.escape(template[last_pos:match.start()])
		var_name = match.group(1)
		expr = match.group(2) or '[^/]+'
		expr = '(?P<%s>%s)' % (var_name, expr)
		regex += expr
		last_pos = match.end()
	regex = re.escape(template[last_pos:])
	regex = '^%s$' % regex
	return regex

def getFileInfo(fname):
	""" Return dictionary with filename, name, extensions and mimetype for file
	"""
	try:
		name, ext = fname.split('.')
	except ValueError, e:
		name, ext = fname, ''
	mtype = mimetypes.guess_type(fname)[0] or 'unkown'
	return {'fname':fname, 'name': name, 'ext':ext, 'mtype':mtype}

from webob import Request, exc
from request import static_controller

class Router(object):
	def __init__(self):
		self.routes = []
		
	def add_route(self, template, controller, **vars):
		self.routes.append((re.compile(template_to_regex(template)),
							controller,
							vars))

	def add_static(self, static_dir):
		for root, dirs, static_content in os.walk(static_dir):
			# Ignore files like something.css~ ?
			for name in static_content:
				info = getFileInfo(name)#name?
				info['fullpath'] = os.path.join(root, name)
				route = ('/').join(info['fullpath'].split('/')[len(static_dir.split('/'))-1:])# do better!
				controller_class = static_controller(info)
				self.add_route('/'+route, controller=controller_class )
							
	def __call__(self, environ, start_response):
		req = Request(environ)
		for regex, controller, vars in self.routes:
			match = regex.match(req.path_info)
			if match:
				req.urlvars = match.groupdict()
				req.urlvars.update(vars)
				return controller(environ, start_response)
		return exc.HTTPNotFound()(environ, start_response)
